package com.ssy.lingxi.member.merchant.serviceimpl.paas;

import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.member.MemberLevelTypeEnum;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.constant.MemberRelationTypeEnum;
import com.ssy.lingxi.member.merchant.api.model.vo.paas.*;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.repository.*;
import com.ssy.lingxi.member.merchant.service.paas.IPaasLevelRightCreditService;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Paas平台 - 设置基础的升级规则、等级、权益、信用等规则接口实现
 * @author 万宁
 * @version 2.0.0
 * @date 2020-08-23
 */
@Service
public class PaasLevelRightCreditServiceImpl implements IPaasLevelRightCreditService {
    @Resource
    private BaseRightConfigRepository baseRightConfigRepository;

    @Resource
    private BaseLevelRuleRepository baseLevelRuleRepository;

    @Resource
    private BaseLevelConfigRepository baseLevelConfigRepository;

    @Resource
    private MemberLevelConfigRepository memberLevelConfigRepository;

    @Resource
    private MemberRightConfigRepository memberRightConfigRepository;

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private BaseCreditConfigRepository baseCreditConfigRepository;

    /**
     * 修改会员权益状态
     *
     * @param configVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateBaseRightStatus(BaseRightConfigStatusVO configVO) {
        BaseRightConfigDO configDO = baseRightConfigRepository.findFirstByRightTypeEnum(configVO.getTypeEnum());
        if(configDO != null) {
            configDO.setStatus(configVO.getStatus());
            baseRightConfigRepository.saveAndFlush(configDO);
        }

        return Wrapper.success();
    }

    /**
     * 更改会员升级规则设置的状态
     *
     * @param ruleVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateBaseLevelRuleConfigStatus(BaseLevelRuleStatusVO ruleVO) {
        BaseLevelRuleDO baseLevelRuleDO = baseLevelRuleRepository.findFirstByRuleTypeEnumAndMemberLevelTypeEnum(ruleVO.getRuleTypeEnum(), ruleVO.getMemberLevelTypeEnum());
        if(baseLevelRuleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_LEVEL_RULE_DOES_NOT_EXIST);
        }

        baseLevelRuleDO.setStatus(ruleVO.getStatus());
        baseLevelRuleRepository.saveAndFlush(baseLevelRuleDO);

        return Wrapper.success();
    }

    /**
     * 新增或修改会员等级（及关联的角色）
     *
     * @param configVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateOrInsertBaseLevelConfig(BaseLevelConfigVO configVO) {
        List<RoleDO> roleList = roleRepository.findAllById(configVO.getRoleIds());
        if(roleList.size() != configVO.getRoleIds().size()) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //这里与创建下级会员的规则相关联，如果创建下级会员的规则变了，这里也要变
        if(configVO.getMemberLevelTypeEnum().equals(MemberLevelTypeEnum.PLATFORM.getCode())) {
            roleList = roleList.stream().filter(roleDO -> !roleDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode())).collect(Collectors.toList());
        } else {
            roleList = roleList.stream().filter(roleDO -> !roleDO.getRelType().equals(MemberRelationTypeEnum.PLATFORM.getCode()) && MemberLevelTypeEnum.getCodeByMemberType(roleDO.getMemberType().getTypeEnum()).equals(configVO.getMemberLevelTypeEnum())).collect(Collectors.toList());
        }

        if(CollectionUtils.isEmpty(roleList)) {
            return Wrapper.success();
        }

        List<BaseLevelConfigDO> levelConfigs = baseLevelConfigRepository.findByMemberLevelTypeEnumAndLevel(configVO.getMemberLevelTypeEnum(), configVO.getLevel());

        List<BaseLevelConfigDO> upsertList = new ArrayList<>();

        for(RoleDO roleDO : roleList) {
            BaseLevelConfigDO configDO = levelConfigs.stream().filter(config -> config.getRole().getId().equals(roleDO.getId())).findFirst().orElse(null);
            if(configDO == null) {
                configDO = new BaseLevelConfigDO();
                configDO.setLevel(configVO.getLevel());
                configDO.setLevelTag(configVO.getLevelTag());
                configDO.setScoreTag(configVO.getScoreTag());
                configDO.setMemberLevelTypeEnum(configVO.getMemberLevelTypeEnum());
                configDO.setRemark(StringUtils.hasLength(configVO.getRemark()) ? configVO.getRemark() : "");
                configDO.setRole(roleDO);
                configDO.setRoleName(roleDO.getRoleName());
                configDO.setStatus(EnableDisableStatus.ENABLE.getCode());
            } else {
                configDO.setLevelTag(configVO.getLevelTag());
                configDO.setScoreTag(configVO.getScoreTag());
                configDO.setRemark(StringUtils.hasLength(configVO.getRemark()) ? configVO.getRemark() : "");
            }
            upsertList.add(configDO);
        }

        baseLevelConfigRepository.saveAll(upsertList);

        return Wrapper.success();
    }

    /**
     * 查询所有基础会员等级设置
     *
     * @return 基础等级设置列表
     */
    @Override
    public Wrapper<List<BaseLevelConfigVO>> listBaseLevelConfig() {
        List<BaseLevelConfigDO> configList = baseLevelConfigRepository.findAll(Sort.by("id").ascending());
        if(CollectionUtils.isEmpty(configList)) {
            return Wrapper.success(new ArrayList<>());
        }

        List<BaseLevelConfigVO> result = new ArrayList<>();
        for (BaseLevelConfigDO baseLevelConfigDO : configList) {
            BaseLevelConfigVO vo = result.stream().filter(v -> v.getLevel().equals(baseLevelConfigDO.getLevel()) && v.getMemberLevelTypeEnum().equals(baseLevelConfigDO.getMemberLevelTypeEnum())).findFirst().orElse(null);
            if(vo == null) {
                vo = new BaseLevelConfigVO();
                vo.setLevel(baseLevelConfigDO.getLevel());
                vo.setMemberLevelTypeEnum(baseLevelConfigDO.getMemberLevelTypeEnum());
                vo.setScoreTag(baseLevelConfigDO.getScoreTag());
                vo.setRemark(baseLevelConfigDO.getRemark());
                vo.setRoleIds(Stream.of(baseLevelConfigDO.getRole().getId()).collect(Collectors.toList()));
                vo.setLevelTag(baseLevelConfigDO.getLevelTag());
                result.add(vo);
            } else {
                vo.getRoleIds().add(baseLevelConfigDO.getRole().getId());
            }
        }

        return Wrapper.success(result);
    }

    /**
     * 删除会员等级
     *
     * @param deleteVO 接口参数
     * @return 更新结果
     */
    @Override
    public Wrapper<Void> deleteBaseLevelConfig(BaseLevelConfigDeleteVO deleteVO) {
        RoleDO roleDO = roleRepository.findById(deleteVO.getRoleId()).orElse(null);
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //由于在新增会员等级的时候，根据创建下级会员的规则做了角色的过滤，所以这里不一定找的到
        //如果为Null，表示Paas的配置不符合规则，返回
        BaseLevelConfigDO configDO = baseLevelConfigRepository.findFirstByRoleAndMemberLevelTypeEnumAndLevel(roleDO, deleteVO.getMemberLevelTypeEnum(), deleteVO.getLevel());
        if(configDO == null) {
            return Wrapper.success();
        }

        baseLevelConfigRepository.delete(configDO);

        return Wrapper.success();
    }

    /**
     * 更新会员等级
     *
     * @param updateVO 接口参数
     * @return 更新结果
     */
    @Override
    public Wrapper<Void> updateBaseLevelConfigStatus(BaseLevelConfigStatusVO updateVO) {
        RoleDO roleDO = roleRepository.findById(updateVO.getRoleId()).orElse(null);
        if(roleDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_ROLE_DOES_NOT_EXIST);
        }

        //由于在新增会员等级的时候，根据创建下级会员的规则做了角色的过滤，所以这里不一定找的到
        //如果为Null，表示Paas的配置不符合规则，返回
        BaseLevelConfigDO configDO = baseLevelConfigRepository.findFirstByRoleAndMemberLevelTypeEnumAndLevel(roleDO, updateVO.getMemberLevelTypeEnum(), updateVO.getLevel());
        if(configDO == null) {
            return Wrapper.success();
        }

        configDO.setStatus(updateVO.getStatus());
        baseLevelConfigRepository.saveAndFlush(configDO);

        return Wrapper.success();
    }

    /**
     * 更改会员信用评估规则权重
     *
     * @param pointVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateMemberCreditConfigPoint(MemberCreditConfigVO pointVO) {
        BaseCreditConfigDO configDO = baseCreditConfigRepository.findFirstByCreditTypeEnum(pointVO.getCreditTypeEnum());
        if(configDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_CREDIT_CONFIG_DOES_NOT_EXIST);
        }

        configDO.setCreditPoint(pointVO.getCreditPoint());
        baseCreditConfigRepository.saveAndFlush(configDO);
        return Wrapper.success();
    }

    /**
     * 更改会员信用评估规则状态
     *
     * @param pointVO 接口参数
     * @return 操作结果
     */
    @Override
    public Wrapper<Void> updateMemberCreditConfigStatus(MemberCreditConfigVO pointVO) {
        BaseCreditConfigDO configDO = baseCreditConfigRepository.findFirstByCreditTypeEnum(pointVO.getCreditTypeEnum());
        if(configDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_CREDIT_CONFIG_DOES_NOT_EXIST);
        }

        configDO.setStatus(pointVO.getStatus());
        baseCreditConfigRepository.saveAndFlush(configDO);
        return Wrapper.success();
    }
}
